<template>
  <div class="flex flex-col h-full bg-white rounded-lg shadow">
    <!-- 设备类型标签 -->
    <div class="p-4">
      <CustomTabs v-model="activeTab" :tabs="tabs" @change="handleTabChange" />
    </div>

    <!-- 表格 -->
    <div class="flex-1 overflow-auto p-4 pb-0">
      <PageState
        :loading="loading"
        :error-message="errorMessage"
        :has-data="filteredTableData.length > 0"
        @retry="retryFetch"
      >
        <el-table
          ref="tableRef"
          :data="filteredTableData"
          style="width: 100%"
          :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }"
        >
        <el-table-column
          prop="deviceName"
          label="Device Name"
          min-width="200"
        />

        <el-table-column label="Status" width="100">
          <template #default="scope">
            <div
              class="flex items-center"
              :style="{ '--status-color': getStatusInfo(scope.row.status).color }"
            >
              <span
                class="inline-block w-2 h-2 rounded-full mr-1.5"
                :style="{ backgroundColor: getStatusInfo(scope.row.status).color }"
              ></span>
              <span>{{ getStatusInfo(scope.row.status).label }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="sn" label="SN" min-width="150" />

        <el-table-column
          prop="deviceType"
          label="Device Type"
          min-width="120"
        />

        <el-table-column prop="product" label="Product" min-width="120" />

        <el-table-column
          label="Operate"
          width="100"
          fixed="right"
          align="center"
        >
          <template #default="scope">
            <el-button type="primary" link @click="handleRename(scope.row)">
              Rename
            </el-button>
          </template>
        </el-table-column>
              </el-table>
      </PageState>
    </div>

    <!-- 分页 -->
    <div class="ml-auto p-4">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        background
        :total="pagination.total"
        :pager-count="5"
        :page-sizes="[10, 20, 50, 100]"
        layout="total,sizes,prev,pager,next,jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 重命名弹窗 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="Rename Device"
      width="500px"
      :before-close="handleCloseRename"
    >
      <el-form
        ref="renameFormRef"
        :model="renameForm"
        :rules="renameRules"
        label-width="120px"
      >
        <el-form-item label="Device name :" prop="deviceName" required>
          <el-input
            v-model="renameForm.deviceName"
            placeholder="Please enter"
            maxlength="50"
            show-word-limit
            @keyup.enter="handleConfirmRename"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseRename">Cancel</el-button>
          <el-button
            type="primary"
            @click="handleConfirmRename"
            :loading="renameLoading"
            style="background-color: #107082; border-color: #107082"
          >
            OK
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElTable } from "element-plus";
import { ref, computed, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import CustomTabs from "@/components/CustomTabs";
import PageState from "@/components/base/PageState.vue";
import { useDebounce } from "@/utils/utils";
import { systemAppApi } from "@/api/business";


const props = defineProps({
  systemId: {
    type: String,
    required: true
  }
});

const route = useRoute();

// 标签配置
const tabs = [
  { name: "all", label: "All device" },
  { name: "energyStorage", label: "Energy storage" },
  { name: "meter", label: "Meter" },
  { name: "appliance", label: "Appliance" },
  { name: "sbv", label: "SBV" }  // 添加SBV选项
];

// 当前激活的标签
const activeTab = ref("all");

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 状态管理
const loading = ref(false);
const errorMessage = ref("");

// 设备数据接口
interface DeviceItem {
  id: number;
  deviceName: string;
  status: string;
  sn: string;
  deviceType: string;
  product: string;
}

// 设备数据
const tableData = ref<DeviceItem[]>([]);
const originalData = ref<DeviceItem[]>([]);

// 设备类型映射
const deviceTypeMap = {
  1: "CT",
  2: "Appliance", 
  3: "储能"
};

// 状态映射 (根据接口文档: 1正常 2离线)
const mapDeviceStatus = (state: number) => {
  if (state === 1) return "normal";
  if (state === 2) return "offline"; 
  return "offline";
};

// 获取设备列表数据
const fetchDeviceList = async () => {
  if (!props.systemId) return;
  
  // 防止重复请求
  if (loading.value) {
    console.log('请求正在进行中，跳过重复请求');
    return;
  }
  
  loading.value = true;
  errorMessage.value = "";
  
  try {
    // 从 systemId 或 route.query 获取 hemsId
    const hemsIdString = String(route.query.hemsId || props.systemId || '');
    const hemsIdNumber = hemsIdString ? parseInt(hemsIdString, 10) : 0;
    
    if (!hemsIdNumber || hemsIdNumber <= 0) {
      throw new Error("无效的 hemsId 参数");
    }
    
    // 构建API参数
    const apiParams: any = { hemsId: hemsIdNumber };
    
    // 根据当前选中的标签添加deviceType参数
    if (activeTab.value !== "all") {
      const deviceTypeMap = {
        energyStorage: 3,  // 储能设备
        meter: 1,          // 电表
        appliance: 2,      // 用电器
        sbv: 4             // SBV设备 (临时值，等API设计好后修改)
      };
      apiParams.deviceType = deviceTypeMap[activeTab.value as keyof typeof deviceTypeMap];
    }
    
    // console.log('API请求参数:', apiParams);
    
    const response = await systemAppApi.getDeviceList(apiParams);
    
    if ((response.code === 0 || response.code === 200) && response.data) {
      // 映射API数据到组件数据结构
      const mappedData = response.data.map((item: any) => ({
        id: item.deviceId || item.id,
        deviceName: item.deviceName || `Device ${item.deviceId}`,
        status: mapDeviceStatus(item.state || 0),
        sn: item.snNumber || item.shortCode || '',
        deviceType: deviceTypeMap[item.deviceType as keyof typeof deviceTypeMap] || "Unknown",
        product: item.shortCode || "Unknown"
      }));
      
      originalData.value = mappedData;
      updateTableData();
    } else {
      throw new Error(response.msg || "获取设备列表失败");
    }
  } catch (error: any) {
    console.error('获取设备列表失败:', error);
    errorMessage.value = error.message || "获取设备列表失败，请稍后重试";
    originalData.value = [];
    updateTableData();
  } finally {
    loading.value = false;
  }
};

// 状态映射
const statusMap = {
  normal: {
    color: "#5AD8A6",
    label: "Normal"
  },
  fault: {
    color: "#F46C6C",
    label: "Fault"
  },
  offline: {
    color: "#909399",
    label: "Offline"
  }
};
type DeviceStatus = keyof typeof statusMap;
function getStatusInfo(status: string) {
  return statusMap[status as DeviceStatus] || statusMap["offline"];
}

// 更新表格数据（现在数据已经通过API筛选，直接使用）
const updateTableData = () => {
  tableData.value = originalData.value;
};

// 过滤后的表格数据（用于分页显示）
const filteredTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 分页信息
const pagination = computed(() => ({
  total: tableData.value.length
}));

// 标签切换 - 使用防抖避免重复请求
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName;
  currentPage.value = 1;
  // 使用防抖重新获取数据，避免快速点击导致的重复请求
  debouncedFetchDeviceList();
};

// 防抖的获取设备列表函数
const debouncedFetchDeviceList = useDebounce(() => {
  fetchDeviceList();
}, 300, { leading: true, trailing: false }); // 300ms防抖，立即执行第一次，忽略后续快速点击

// 分页切换 - 使用防抖避免重复请求
const handlePageChange = (page: number) => {
  currentPage.value = page;
  // 分页切换时不需要重新请求API，因为数据已经通过API筛选了
  // 只需要更新显示的数据即可
};

// 页面大小切换 - 使用防抖避免重复请求
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  // 页面大小切换时不需要重新请求API，因为数据已经通过API筛选了
  // 只需要更新显示的数据即可
};

// 重命名相关
const renameDialogVisible = ref(false);
const renameLoading = ref(false);
const currentRenameDevice = ref<DeviceItem | null>(null);
const renameFormRef = ref();

// 重命名表单
const renameForm = ref({
  deviceName: ""
});

// 表单验证规则
const renameRules = {
  deviceName: [
    { required: true, message: "Device name is required", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "Device name length should be 1-50 characters",
      trigger: "blur"
    }
  ]
};

// 重命名操作
const handleRename = (row: DeviceItem) => {
  currentRenameDevice.value = row;
  renameForm.value.deviceName = row.deviceName;
  renameDialogVisible.value = true;
};

// 关闭重命名弹窗
const handleCloseRename = () => {
  renameDialogVisible.value = false;
  renameForm.value.deviceName = "";
  currentRenameDevice.value = null;
  if (renameFormRef.value) {
    renameFormRef.value.resetFields();
  }
};

// 确认重命名
const handleConfirmRename = async () => {
  if (!renameFormRef.value) return;

  try {
    await renameFormRef.value.validate();
    renameLoading.value = true;

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 更新设备名称
    if (currentRenameDevice.value) {
      const deviceIndex = tableData.value.findIndex(
        item => item.id === currentRenameDevice.value!.id
      );
      if (deviceIndex !== -1) {
        tableData.value[deviceIndex].deviceName = renameForm.value.deviceName;
      }
    }

    // 关闭弹窗
    handleCloseRename();

    // 显示成功消息
    console.log("Device renamed successfully!");
  } catch (error) {
    console.error("Rename validation failed:", error);
  } finally {
    renameLoading.value = false;
  }
};

// 表格引用
const tableRef = ref<typeof ElTable | null>(null);

// 重试加载
const retryFetch = () => {
  fetchDeviceList();
};

// 监听 systemId 变化
watch(() => props.systemId, (newSystemId) => {
  if (newSystemId) {
    fetchDeviceList();
  }
}, { immediate: true });

// 组件挂载时获取数据
onMounted(() => {
  fetchDeviceList();
});

// 防抖搜索
const debouncedSearch = useDebounce(() => {
  // 这里可以添加搜索逻辑
  console.log("搜索设备...");
}, 500, { leading: false, trailing: true });
</script>

<style scoped lang="scss">
/* 调整分页组件样式 */
:deep(.el-pagination) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: auto;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: auto;
}

// 取消分页器非活跃按钮的背景色
:deep(.el-pagination .el-pager li) {
  background-color: transparent;
}
</style>
